const http= require("http");
const fs= require("fs");
const path= require("path");
const mime= require("mime");
var cache= {};  //用来缓存文件内容的对象

const chatServer= require("./lib/chat_server");

// 1
//错误响应
function send404(response){
    response.writeHead(404, { "Content-Type": "text/plain" });
    response.write("Error 404: resource not found.");
    response.end();
}
//发送文件数据
function sendFile(response, filePath, fileContents){
    response.writeHead(
        200,
        {"content-type":mime.getType(path.basename(filePath))}
    );
    response.end(fileContents);
}

//提供静态文件服务
function serveStatic(response, cache, absPath) {
    if(cache[absPath]){
        sendFile(response, absPath, cache[absPath]);
    } else{
        fs.exists(absPath, function(exists){
            if(exists){
                fs.readFile(absPath, function(err, data){
                    if(err){
                        send404(response);
                    } else{
                        cache[absPath]= data;
                        sendFile(response, absPath, data);
                    }
                });
            } else{
                send404(response);
            }
        })
    }
}

//创建http服务器的逻辑
var server= http.createServer(function(request, response){
    var filePath= false;
    var absPath;
    if(request.url== '/'){
        filePath= "public/index.html";
        absPath= "../"+filePath;
    } else{
        filePath= "public"+request.url;
        absPath= "./"+filePath;
    }
    console.log('访问：',absPath);
    serveStatic(response, cache, absPath);
})

server.listen(3003, function(){
    console.log("server listening on port 3003.");
})

chatServer.listen(server);
